﻿using AutoMapper;
using B.S.BaseData.Domain;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Read.Api.Application.Command;
using B.S.BaseData.Read.Api.Dtos;
using MediatR;
using SqlSugar;

namespace B.S.BaseData.Read.Api.Application.CommandHander
{
    public class AdditiveRoleCommandHander : IRequestHandler<AdditiveRoleCommand, ApiResult<List<AdditiveRoleDto>>>
    {

        private readonly IMapper mapper;
        private readonly ISqlSugarClient db;

        public AdditiveRoleCommandHander(IMapper mapper, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.db = db;
        }

        /// <summary>
        /// 反添角色权限操作
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<List<AdditiveRoleDto>>> Handle(AdditiveRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<AdditiveRoleDto>> result = new ApiResult<List<AdditiveRoleDto>>();

            var linq = db.Queryable<Role>()
                .InnerJoin<RoleMenu>((r, rm) => r.RoleId == rm.RoleId)
                .InnerJoin<Menu>((r, rm, m) => rm.MenuId == m.Id)
                .Where((r, rm, m) => request.RoleId == rm.RoleId)
                .Select((r, rm, m) => new AdditiveRoleDto
                {
                    RoleId = r.RoleId,
                    RoleName = r.RoleName,
                    Id = m.Id,
                    MenuName = m.MenuName
                });

            result.Code = ApiEnum.显示成功;
            result.Msg = ApiEnum.显示成功.ToString();
            var entity = linq.OrderBy(r => r.RoleId).ToList();

            result.Data = mapper.Map<List<AdditiveRoleDto>>(entity);

            return Task.FromResult(result);

        }
    }
}
